class App {
    constructor() {
        this.digitalHuman = null;
        this.socket = null;
        this.audioContext = null;
        this.currentAudio = null;
        
        this.init();
    }

    init() {
        console.log('初始化应用程序...');
        
        // 初始化3D数字人
        const container = document.getElementById('canvas-container');
        console.log('容器元素:', container);
        
        if (!container) {
            console.error('找不到canvas-container元素');
            return;
        }
        
        // 根据页面选择不同的数字人模型
        if (window.location.pathname.includes('image-to-3d')) {
            // 图片转3D页面使用特殊的初始化方式
            console.log('检测到图片转3D页面，跳过自动初始化');
            return;
        } else if (window.location.pathname.includes('realistic-girl')) {
            this.digitalHuman = new RealisticDigitalHuman(container);
        } else {
            this.digitalHuman = new DigitalHuman(container);
        }
        console.log('3D数字人已创建');
        
        // 初始化WebSocket连接
        this.initSocket();
        
        // 初始化音频上下文
        this.initAudio();
        
        // 绑定事件
        this.bindEvents();
        
        // 更新状态
        this.updateStatus('系统已就绪');
        
        console.log('应用程序初始化完成');
    }

    initSocket() {
        this.socket = io();
        
        this.socket.on('connect', () => {
            console.log('已连接到服务器');
            this.updateStatus('已连接到服务器');
        });
        
        this.socket.on('audioReady', (data) => {
            this.handleAudioReady(data);
        });
        
        this.socket.on('startSpeaking', (data) => {
            this.handleStartSpeaking(data);
        });
        
        this.socket.on('error', (error) => {
            this.handleError(error);
        });
        
        this.socket.on('disconnect', () => {
            this.updateStatus('与服务器断开连接');
        });
    }

    initAudio() {
        try {
            this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
        } catch (error) {
            console.warn('音频上下文初始化失败:', error);
        }
    }

    bindEvents() {
        // 说话按钮
        const speakBtn = document.getElementById('speakBtn');
        const textInput = document.getElementById('textInput');
        
        speakBtn.addEventListener('click', () => {
            this.handleSpeak();
        });
        
        // 回车键说话
        textInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.handleSpeak();
            }
        });
        
        // 控制面板
        const rotationSpeed = document.getElementById('rotationSpeed');
        const animationIntensity = document.getElementById('animationIntensity');
        const expressionIntensity = document.getElementById('expressionIntensity');
        
        rotationSpeed.addEventListener('input', () => {
            this.updateControls();
        });
        
        animationIntensity.addEventListener('input', () => {
            this.updateControls();
        });
        
        expressionIntensity.addEventListener('input', () => {
            this.updateControls();
        });
        
        // 页面可见性变化时暂停/恢复音频
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                this.pauseAudio();
            } else {
                this.resumeAudio();
            }
        });
    }

    handleSpeak() {
        const textInput = document.getElementById('textInput');
        const text = textInput.value.trim();
        
        if (!text) {
            this.updateStatus('请输入要说的内容');
            return;
        }
        
        if (text.length > 200) {
            this.updateStatus('文本长度不能超过200个字符');
            return;
        }
        
        // 显示加载状态
        this.showLoading(true);
        this.updateStatus('正在生成语音...');
        
        // 禁用按钮
        const speakBtn = document.getElementById('speakBtn');
        speakBtn.disabled = true;
        
        // 发送到服务器
        this.socket.emit('speak', { text });
    }

    handleAudioReady(data) {
        console.log('音频已准备就绪:', data);
        
        // 播放音频
        this.playAudio(data.audioUrl);
        
        // 隐藏加载状态
        this.showLoading(false);
        
        // 启用按钮
        const speakBtn = document.getElementById('speakBtn');
        speakBtn.disabled = false;
        
        this.updateStatus('语音生成完成');
    }

    handleStartSpeaking(data) {
        console.log('开始说话:', data);
        
        // 开始数字人说话动画
        this.digitalHuman.startSpeaking(data.duration);
        
        this.updateStatus(`正在说话: "${data.text}"`);
    }

    handleError(error) {
        console.error('错误:', error);
        
        // 隐藏加载状态
        this.showLoading(false);
        
        // 启用按钮
        const speakBtn = document.getElementById('speakBtn');
        speakBtn.disabled = false;
        
        this.updateStatus(`错误: ${error.message}`);
    }

    async playAudio(audioUrl) {
        try {
            // 停止当前音频
            this.stopAudio();
            
            // 创建新的音频元素
            const audio = new Audio(audioUrl);
            audio.crossOrigin = 'anonymous';
            
            // 音频事件处理
            audio.addEventListener('loadstart', () => {
                this.updateStatus('正在加载音频...');
            });
            
            audio.addEventListener('canplay', () => {
                this.updateStatus('音频加载完成，开始播放');
            });
            
            audio.addEventListener('ended', () => {
                this.updateStatus('播放完成');
                this.digitalHuman.stopSpeaking();
            });
            
            audio.addEventListener('error', (e) => {
                console.error('音频播放错误:', e);
                this.updateStatus('音频播放失败');
                this.digitalHuman.stopSpeaking();
            });
            
            // 播放音频
            await audio.play();
            this.currentAudio = audio;
            
        } catch (error) {
            console.error('播放音频失败:', error);
            this.updateStatus('音频播放失败');
            this.digitalHuman.stopSpeaking();
        }
    }

    stopAudio() {
        if (this.currentAudio) {
            this.currentAudio.pause();
            this.currentAudio.currentTime = 0;
            this.currentAudio = null;
        }
    }

    pauseAudio() {
        if (this.currentAudio && !this.currentAudio.paused) {
            this.currentAudio.pause();
        }
    }

    resumeAudio() {
        if (this.currentAudio && this.currentAudio.paused) {
            this.currentAudio.play().catch(console.error);
        }
    }

    updateControls() {
        const rotationSpeed = parseFloat(document.getElementById('rotationSpeed').value);
        const animationIntensity = parseFloat(document.getElementById('animationIntensity').value);
        const expressionIntensity = parseFloat(document.getElementById('expressionIntensity').value);
        
        this.digitalHuman.updateControls(rotationSpeed, animationIntensity, expressionIntensity);
    }

    showLoading(show) {
        const loading = document.getElementById('loading');
        if (show) {
            loading.classList.add('show');
        } else {
            loading.classList.remove('show');
        }
    }

    updateStatus(message) {
        const status = document.getElementById('status');
        status.textContent = message;
        
        // 3秒后清除状态消息（除非是错误消息）
        if (!message.includes('错误') && !message.includes('失败')) {
            setTimeout(() => {
                if (status.textContent === message) {
                    status.textContent = '准备就绪';
                }
            }, 3000);
        }
    }

    // 添加一些预设的对话
    addPresetButtons() {
        const presets = [
            '你好！我是真实感的AI少女！',
            '我的样子是不是很真实呢？',
            '喜欢我的新造型吗？',
            '今天天气真不错！',
            '我们可以聊聊天哦！',
            '谢谢你的关注！',
            '希望你喜欢这个真实的我！'
        ];
        
        const presetContainer = document.createElement('div');
        presetContainer.style.marginTop = '10px';
        presetContainer.style.display = 'flex';
        presetContainer.style.flexWrap = 'wrap';
        presetContainer.style.gap = '5px';
        
        presets.forEach(preset => {
            const btn = document.createElement('button');
            btn.textContent = preset;
            btn.style.padding = '5px 10px';
            btn.style.fontSize = '12px';
            btn.style.border = '1px solid #ddd';
            btn.style.borderRadius = '15px';
            btn.style.background = 'white';
            btn.style.cursor = 'pointer';
            btn.style.transition = 'all 0.2s';
            
            btn.addEventListener('mouseenter', () => {
                btn.style.background = '#f0f0f0';
            });
            
            btn.addEventListener('mouseleave', () => {
                btn.style.background = 'white';
            });
            
            btn.addEventListener('click', () => {
                document.getElementById('textInput').value = preset;
                this.handleSpeak();
            });
            
            presetContainer.appendChild(btn);
        });
        
        document.getElementById('ui-panel').appendChild(presetContainer);
    }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    const app = new App();
    
    // 添加预设按钮
    setTimeout(() => {
        app.addPresetButtons();
    }, 1000);
    
    // 全局错误处理
    window.addEventListener('error', (e) => {
        console.error('全局错误:', e.error);
    });
    
    window.addEventListener('unhandledrejection', (e) => {
        console.error('未处理的Promise拒绝:', e.reason);
    });
});
